package ipebg.mzk.provider.system.service.impl;
import ipebg.mzk.common.util.Page;
import ipebg.mzk.facade.entity.MsAdminUser;
import ipebg.mzk.facade.entity.Org;
import ipebg.mzk.facade.entity.OrgLevel;
import ipebg.mzk.facade.system.bean.OrgBean;
import ipebg.mzk.facade.system.bean.OrgTreeBean;
import ipebg.mzk.facade.system.service.OrgService;
import ipebg.mzk.facade.system.service.PagerService;
import ipebg.mzk.facade.system.service.UserService;
import ipebg.mzk.provider.system.dao.OrgDao;
import ipebg.mzk.provider.system.dao.OrgLevelDao;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service("orgServiceImpl")
@Transactional(rollbackFor = Exception.class)
public class OrgServiceImpl implements OrgService{
	private static final Log log = LogFactory.getLog(OrgServiceImpl.class);
	
	@SuppressWarnings("rawtypes")
	@Resource(name = "pageServiceImpl")
	private PagerService pageService;
	
	@Resource(name = "orgDao")
	private OrgDao orgDao;
	
	@Resource(name = "orgLevelDao")
	private OrgLevelDao orgLevelDao;
	
	@Resource(name = "userServiceImpl")
	private UserService userService;

	@SuppressWarnings("unchecked")
	public List<OrgLevel> getOrgLevelList() {
		String hql="from OrgLevel order by levelNumber desc";
		return orgLevelDao.queryForList(hql,null);
		 
	}

	public boolean saveOrUpdateOrg(Org entity) {
		boolean flag = false;
		try {
			orgDao.saveOrUpdate(entity);		
			flag = true;
		} catch (RuntimeException re) {
			re.printStackTrace();
		} catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}

	public Page getAllList(OrgBean bean ,int from, int length) throws Exception {
		Page list = null;
		String hql = " from Org o where 1=1 ";
		if(bean != null){
			if(bean.getOrgCode() !=null && !bean.getOrgCode().equals("")){
				hql += " and o.orgCode like '%"+bean.getOrgCode().trim()+"%'";
			}
			if(bean.getOrgName() !=null && !bean.getOrgName().equals("")){
				hql += " and o.orgName like '%"+bean.getOrgName().trim()+"%'";
			}
			if(bean.getEnable() !=null && !bean.getEnable().equals("")){
				hql += " and o.enable like '%"+bean.getEnable()+"%'";
			}
			if(bean.getDominate() !=null && !bean.getDominate().equals("")){
				hql += " and o.dominate like '%"+bean.getDominate()+"%'";
			}
			if(bean.getLevelId() !=null && !bean.getLevelId().equals("")){
				hql += " and o.levelId like '%"+bean.getLevelId()+"%'";
			}
		}
		hql +=" order by o.modifyTime desc ";
		log.info("query For Org List:"+hql);
		try {
			list = pageService.findPageByhqlQuery(from, length, hql);
		} catch (Exception e) {
			throw e;
		}		
		return list;
	}

	@Override
	public List<OrgBean> toBean(List<Org> list) {
		List<OrgBean> beanList = new ArrayList<OrgBean>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for(Org entity:list) {
			OrgBean bean = new OrgBean();
			bean.setOrgId(entity.getOrgId());
			bean.setDominate(entity.getDominate());
			bean.setOrgCode(entity.getOrgCode());
			bean.setOrgName(entity.getOrgName());
			bean.setOrgFee(entity.getOrgFee());
			bean.setLevelId(entity.getLevelId());
			OrgLevel level = orgLevelDao.findById(entity.getLevelId());
			bean.setLeaderNo(entity.getLeaderNo());
			bean.setLevelName(level.getLevelName());
			bean.setLeaderName(entity.getLeaderName());
			if(entity.getParentId()!=null && !entity.getParentId().equals("")) {
				bean.setParentId(entity.getParentId());
				Org org = orgDao.findById(entity.getParentId());
				System.out.println(org.getOrgId());
				System.out.println(org.getLevelId());
				bean.setParentCode(org.getOrgCode());
				bean.setParentName(org.getOrgName());
			}
			bean.setEnable(entity.getEnable());
			MsAdminUser user = userService.findUserByEmpNo(entity.getCreateName());
			if (user != null) {
				bean.setCreateName(user.getRealName());
			}
			//bean.setCreateName(entity.getCreateName());
			bean.setCreateTime(sdf.format(entity.getCreateTime()));
			if(!(entity.getModifyName()==null||entity.getModifyName().equals(null)||entity.getModifyName().equals(""))){
				MsAdminUser u = userService.findUserByEmpNo(entity.getModifyName());
				if (u != null) {
					bean.setCreateName(u.getRealName());//
				}
			}else
				bean.setModifyName("");
			//bean.setModifyName(entity.getModifyName());
			bean.setModifyTime(sdf.format(entity.getModifyTime()));
			beanList.add(bean);
		}
		return beanList;
	}

	@Override
	public Org findById(String id) {
		return orgDao.findById(id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Org findByCode(String orgCode) {
		//List<Org> list = (List<Org>)orgDao.findByProperty("orgCode", orgCode, null);
		List<Org> list = (List<Org>)orgDao.findByProperty(Org.class,new String[]{"orgCode"}, new Object[]{orgCode});
		if(list!=null && list.size()!=0) {
			return list.get(0);
		} else {
			return null;
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List findByCode(String levelNumber, String orgCode) {
		String sql = "select o.* from TB_COMMON_ORG o left join TB_COMMON_ORG_LEVEL ol on (o.ORG_LEVEL_ID = ol.LEVEL_ID)" +
				" where o.ORG_CODE = '"+orgCode+"' and ol.LEVEL_NUMBER = '"+levelNumber+"'";
		return orgDao.findBySQL(sql, new String[]{});
	}

	
	@Override
	public OrgLevel findOrgLevelById(String levelId) {
		return orgLevelDao.findById(levelId);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<OrgLevel> getOrgLevelList(String levelName) {
		//List<OrgLevel> orgLevellist = orgLevelDao.findByProperty("levelName", levelName, null);
		List<OrgLevel> orgLevellist = orgLevelDao.findByProperty(OrgLevel.class,new String[]{"levelName"}, new Object[]{levelName});
		if(orgLevellist != null && orgLevellist.size() != 0){
			return orgLevellist;
		} else {
			return null;
		}
	}
	
	@Override
	public boolean delOrg(String id) {
		boolean flag = false;
		try {
			Org org = new Org();
			org.setOrgId(id);
			//orgDao.delete(orgDao.findById(id));
			orgDao.delete(org);
			flag = true;
		} catch (RuntimeException re) {
			re.printStackTrace();
		} catch(Exception e){
			e.printStackTrace();
		}
		return flag;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Org> getAllList() {
	/*	String[] orderStrings = {"createTime desc"}; 
		return orgDao.findAll(orderStrings);*/
		String hql="from Org order by createTime desc";
	    return orgDao.queryForList(hql,null);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<OrgTreeBean> getOrgTreeList(String parentId) {
		List<OrgTreeBean> list = null;
		String select = "select o.orgId,o.orgName,o.orgCode from Org o where  o.enable = '1' and o.parentId = ? order by createTime desc";
		List oList = orgDao.queryForList(select,new String[]{parentId});
		if(oList!=null) {
			list = new ArrayList<OrgTreeBean>();
			for(Object o:oList) {
				OrgTreeBean bean = new OrgTreeBean();
				Object[] oo = (Object[])o;
				bean.setId((String)oo[0]);
				String text = (String)oo[1] + "(" + (String)oo[2] + ")";
				bean.setText(text);
				bean.setChecked(false);
				List<OrgTreeBean> children = getOrgTreeList((String)oo[0]);
				bean.setChildren(children);
				list.add(bean);
			}
		}
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Org> getExcelReporterList(Org org) {
		String hql = "from Org o where o.orgId is not null";
		if(org != null){
			if(org.getOrgCode() !=null && !org.getOrgCode().equals("")){
				hql += " and o.orgCode like '%"+org.getOrgCode().trim()+"%'";
			}
			if(org.getOrgName() !=null && !org.getOrgName().equals("")){
				hql += " and o.orgName like '%"+org.getOrgName().trim()+"%'";
			}
			if(org.getEnable() !=null && !org.getEnable().equals("")){
				hql += " and o.enable like '%"+org.getEnable()+"%'";
			}
		}
		
		hql +=" order by o.modifyTime desc,o.createTime desc ";
		log.info("query For Org List:"+hql);
		
		return orgDao.queryForList(hql, null);
		
	}
	
	@Override
	public List<Org> findOrgByLevelId(String levelId){
		return orgDao.findByProperty(Org.class, new String[]{"levelId"}, new Object[]{levelId});
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Org> findEnableOrgByLevelNum(Integer levelNumber) {
		String hql = "select o from Org o,OrgLevel ol where o.levelId = ol.levelId and o.enable = '1' and ol.levelNumber = "+levelNumber+"";
		log.info("query For Org List:"+hql);
		return orgDao.queryForList(hql,null);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Org> findChildrenByParentId(String parentId, Integer levelNumber) {
		String hql = "select o from Org o,OrgLevel ol where o.levelId = ol.levelId and o.parentId = '"+parentId+"' and o.enable = '1' and ol.levelNumber = "+levelNumber+"";
		log.info("query For Org List:"+hql);
		return orgDao.queryForList(hql, null);
	}
	
	@Override
	public List<Org> findChildrenByParentId(String dominate, String orgId,
			Integer levelNumber) {
		String hql = "select o from Org o,OrgLevel ol where o.levelId = ol.levelId and o.parentId = '"+orgId+"' and o.enable = '1' and ol.levelNumber = "+levelNumber+"";
		if(dominate != null && !dominate.equals("")){
			hql += " and o.dominate = '"+dominate+"'";
		}
		log.info("query For Org List:"+hql);
		return orgDao.queryForList(hql, null);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Org> findChildrenByParentId1(String parentId, String dominate, Integer levelNumber) {
		String hql = "select o from Org o,OrgLevel ol where o.levelId = ol.levelId and o.dominate = '"+dominate+"' and o.parentId = '"+parentId+"' and o.enable = '1' and ol.levelNumber = "+levelNumber+"";
		log.info("query For Org List:"+hql);
		return orgDao.queryForList(hql, null);
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<Org> getOrgBeanList(Org org) {
		String hql = "from Org o where o.orgId is not null";
		if(org != null){
			if (org.getEnable() != null && !org.getEnable().trim().equals("")) {
				hql += " and o.enable = '"+org.getEnable()+"'";
			}
			if (org.getDominate() != null && !org.getDominate().trim().equals("")) {
				hql += " and o.dominate = '"+org.getDominate()+"'";
			}
			if (org.getLevelId() != null && !org.getLevelId().trim().equals("")) {
				hql += " and o.levelId = '"+org.getLevelId()+"'";
			}
			if (org.getOrgCode() != null && !org.getOrgCode().trim().equals("")) {
				hql += " and o.orgCode = '"+org.getOrgCode()+"'";
			}
			if (org.getParentId() != null && !org.getParentId().trim().equals("")) {
				hql += " and o.parentId = '"+org.getParentId()+"'";
			}
		}
		
		log.info("query For Org List:"+hql);
		return orgDao.queryForList(hql, null);
	}

	@Override
	public List<Org> findByDominate(String dominate,int level) {
		String hql = "select o from Org o,OrgLevel ol where o.levelId = ol.levelId and o.dominate = '"+dominate+"' and o.enable = '1' and ol.levelNumber = "+level+"";
		log.info("query For Org List:"+hql);
		return orgDao.queryForList(hql, null);
	}

	@Override
	public List<Org> findOrgByTwo(String orgLevelId, String dominate) {
	    List<Org> list = orgDao.findByProperty(Org.class, new String[]{"levelId","dominate"},new Object[]{orgLevelId,dominate});
		return list;

	}

	@Override
	public Org findOrg(String factoryName, String deptName) {
		Org org = null;
		List<Org> list = orgDao.findByProperty(Org.class, new String[]{"dominate","orgName"},new Object[]{factoryName,deptName});
		if(list.size() == 1){
			org = list.get(0);
		}
		return org;
	}

	
}
